/**
 * Created by lwy on 2017/8/30.
 */


var details;
var ifSpeImg = 'false';
var fenqiId;
var  specificationName,
    prepayment,
    periods,
    instalmentAmount,
    goodsName,
    fenqiState;

$(function () {
    var id= $('#idBox').html();
    getCrmDetails(id);
    $('#update').show();
})

function getCrmDetails(id) {
    $.ajax({
        url: '/crm/integralGoods/detail.json',
        dataType: 'json',
        data: {
            token: localStorage.getItem('crmtoken'),
            id: id,
        },
        success: function (data) {
            if (data.code == -1) {
                window.parent.location.href = "/crm/login.jsp";
            }
            if (data.code == 0) {
                alert(data.msg);
            }
            if (data.code == 1) {
                var data = data.datas;
                $('#name').val(data.name);
                $('#sumary').val(data.abbreviation);
                $('#inventory').val(data.inventory);
                $('#totalIntegral').val(data.totalIntegral);
                var morePic = data.mainImg.split(',');
                console.log(morePic.length);
                if(morePic.length>1){
                    for(var i=0;i<morePic.length-1;i++){
                        $('<div class="oneImgBox"><img src="'+morePic[i]+'" ifShow="true"/><span>×</span></div>').appendTo($('#imgBox'))
                    }
                }else{
                    $('<div class="oneImgBox"><img src="'+morePic[0]+'" ifShow="true"/><span>×</span></div>').appendTo($('#imgBox'))
                }
                $('.oneImgBox span').click(function () {
                    $(this).parent().empty().hide();
                })
                //$('#mainImg').attr('src', data.mainImg);
                var details = data.detailsImg;
                var ue = UE.getEditor('container', {
                    autoHeight: false,
                    initialFrameHeight:800
                });
                ue.addListener("ready",function(){
                    // editor准备好之后才可以使用  
                    ue.setContent(data.detailsImg);

                });
                $('#unitIntegral').val(data.unitIntegral);
                $('#safeguard').find('div[contenteditable="true"]').html(data.safeguard);
                $('#parameter').find('div[contenteditable="true"]').html(data.parameter);
                $("#goodsTypeValue").val(data.goodsTypeValue)
                $("#stateValue").val(data.stateValue)
                $('#warrantyPeriod').val(data.warrantyPeriod);
                details = data.detailsImg;
                $('#detailImg img').load(function () {
                    $('#detailImg img').css({'width': '40px', 'height': '40px', 'margin-right': '10px'})
                })
                if (data.goodsTypeValue == 1) {

                    $('#totalIntegralHiden').hide();
                }
                //点击放大图片
                $('#mainImg,#detailImg img').click(function () {
                    var src = $(this).attr('src');
                    $('#bigImg').attr('src', src);
                    $('#closeImg').show();
                })
                $('#closeImg,#close2').click(function () {
                    $('#closeImg').hide();
                })
            }
        }
    })

}


$(document).on('click','.oneImgBox span',function () {
    $(this).parent().empty().hide();
})

$('#scope').focus(function () {
    $('#scopeText').show();
})





//上传主图
var mainImg;
$('#avatarInput').on('change', function (e) {
    var filemaxsize = 1024 * 5;//5M
    var target = $(e.target);
    var Size = target[0].files[0].size / 1024;
    if (Size > filemaxsize) {
        alert('图片过大，请重新选择!');
        $(".avatar-wrapper").childre().remove;
        return false;
    }
    if (!this.files[0].type.match(/image.*/)) {
        alert('请选择正确的图片!')
    } else {
        var filename = document.querySelector("#avatar-name");
        var texts = document.querySelector("#avatarInput").value;
        var teststr = texts; //你这里的路径写错了
        testend = teststr.match(/[^\\]+\.[^\(]+/i); //直接完整文件名的
        filename.innerHTML = testend;
    }

});


$(".avatar-save").on("click", function () {
    var img_lg = document.getElementById('imageHead');
    // 截图小的显示框内的内容
    html2canvas(img_lg, {
        allowTaint: true,
        taintTest: false,
        onrendered: function (canvas) {
            canvas.id = "mycanvas";
            //生成base64图片数据
            var dataUrl = canvas.toDataURL("image/jpeg");
            var newImg = document.createElement("img");
            newImg.src = dataUrl;
            imagesAjax(dataUrl)
        }
    });
})

//保存修改
$('#save').click(function () {
    if ($('#avatar-name').html() == "") {
        alert('请选择图片');
    } else {
        $('#save').attr('data-dismiss', 'modal')
    }
})

function imagesAjax(src) {
    var data = {};
    data.img = src;
    data.jid = $('#jid').val();
    mainImg = src;

    $.ajax({
        url: '/crm/image/uploadImage.json',
        data: {
            filed: mainImg,
        },
        dataType: 'json',
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                //$('#mainImg').show();
                $('#mainImg').attr('src', data.datas.path);
                //$('#update').html('更换')
            }
        }
    })
}

var imgs = "";
var IMG = 0;
var IMG2 = 0;
var yuanImg = '';

function changeImg() {
    selectOver2();
}

function selectOver2() {
    IMG2++;
    $.ajaxFileUpload({
        url: '/crm/uploadImage.do?isDetail=true',
        type: 'POST',
        fileElementId: 'imageUpload',
        dataType: 'JSON',
        success: function (data) {
            var results = data.split('|');
            var flag = results[0].split('>');
            if (flag[1] != 'success') {
                mui.alert('上传失败');
                IMG2--;
                return;
            }
            var img = results[1].substring(results[1].length - 6, 0);
            if (yuanImg == "") {
                yuanImg = img;
            } else {
                yuanImg = yuanImg + ',' + img;
            }

            var imgLength = yuanImg.split(',');
            var imgHtml = '';
            for (var i = 0; i < imgLength.length; i++) {
                imgHtml += '<img src="' + imgLength[i] + '" alt="img" style="width: 90%"/>'
            }
            $('#target').val(imgHtml);
            $('#content').html(imgHtml);


        },
        error: function (data) {
            IMG2--;
            mui.alert('上传失败');

        }
    })
}

//更改商品详情
$('.editDetail').click(function () {
    $('#detailBox').show();
    $('#content').html(details);
    $('#target').val(details);
})

//修改
$('#editAll').click(function () {
    $('#editAll').hide();
    $('#detailBox').show();
    $('#content').html(details);
    $('#target').val(details);
    $('input').removeAttr('readonly');
    $('#inventory').attr('readonly', true);
    $('#ifCash').hide();
    $('#ifCashSelect').show();
    $('#delivery').hide();
    $('#clock').show();
    $('#update').show();
    //$('#save').show();
    $('#save2').show();

})

//保存修改
$('#save2').click(function () {
    var mainImg = '';

    $(".oneImgBox img[ifShow=true]").each(function(i){
        mainImg+=$(this).attr("src")+","
    });
    if(mainImg=="../static/img/uploadImg.png"){
        mainImg='';
    }

    console.log(mainImg);
    var ue2 = UE.getEditor('container', {
        autoHeight: false,
        initialFrameHeight:800
    });

    function getContent() {
        var html = ue2.getContent();
        return html;
    }
    var details  = getContent();
    $.ajax({
        url: '/crm/integralGoods/update.json',
        dataType: 'json',
        data: {
            abbreviation: $('#sumary').val(),
            name: $('#name').val(),
            mainImg: mainImg,
            unitIntegral: $('#unitIntegral').val(),
            totalIntegral:$('#totalIntegral').val(),
            inventory:$('#inventory').val(),
            state:$('#stateValue').val(),
            detailsImg: details,
            id: $('#idBox').html(),
            token: localStorage.getItem('crmtoken'),
        },
        type: 'post',
        success: function (data) {
            if (data.code == 0) {
                alert(data.msg);
            }
            if (data.code == -1) {
                window.parent.location.href = "/crm/login.jsp"
            }
            if (data.code == 1) {
                alert('修改申请成功')
            }
        }
    })
})




var speBigId = '';
var speSmallId = '';
//编辑单个
$('body').on('dblclick', '.db_input', function () {
    $(this).removeAttr('readonly');
    if ($(this).hasClass('bigSpe')) {
        $(this).parent().append('<img class="title_del" src="../static/img/close-spe.png"/>')
        $(this).parent().parent().siblings().find('img').hide();
        speBigId = $(this).attr('id');
        speSmallId = '';
    } else {
        $(this).parent().append('<img class="spe_del" src="../static/img/close-spe.png"/>')
        $(this).parent().parent().siblings().find('img').hide();
        speSmallId = $(this).attr('id');
        speBigId = '';
    }
})
$('body').on('blur', '.db_input', function () {
    $(this).attr('readonly', true);
    if ($(this).hasClass('bigSpe')) {
        speSmallId = '';

    } else {
        speBigId = '';

    }
})













//上传主图
var mainImg;
$('#avatarInput').on('change', function(e) {
    var filemaxsize = 1024 * 5;//5M
    var target = $(e.target);
    var Size = target[0].files[0].size / 1024;
    if(Size > filemaxsize) {
        alert('图片过大，请重新选择!');
        $(".avatar-wrapper").childre().remove;
        return false;
    }
    if(!this.files[0].type.match(/image.*/)) {
        alert('请选择正确的图片!')
    } else {
        var filename = document.querySelector("#avatar-name");
        var texts = document.querySelector("#avatarInput").value;
        var teststr = texts; //你这里的路径写错了
        testend = teststr.match(/[^\\]+\.[^\(]+/i); //直接完整文件名的
        filename.innerHTML = testend;
    }

});



$(".avatar-save").on("click", function() {
    var img_lg = document.getElementById('imageHead');
    // 截图小的显示框内的内容
    html2canvas(img_lg, {
        allowTaint: true,
        taintTest: false,
        onrendered: function(canvas) {
            canvas.id = "mycanvas";
            //生成base64图片数据
            var dataUrl = canvas.toDataURL("image/jpeg");
            var newImg = document.createElement("img");
            newImg.src = dataUrl;
            imagesAjax(dataUrl)
        }
    });
})

function imagesAjax(src) {
    var data = {};
    data.img = src;
    data.jid = $('#jid').val();
    mainImg = src;

    $.ajax({
        url:'/crm/image/uploadImage.json',
        data:{
            filed:mainImg,
        },
        dataType:'json',
        type:'post',
        success:function(data){
            if(data.code==1){
                $('#mainImg,#mainImg2').show();
                $('#mainImg,#mainImg2').attr('src',data.datas.path);
                $('#update,#update2').html('更换')
            }
        }
    })
}
$('#update2').click(function () {
    ifSpeImg = 'true';
    $('#imageHead').css({'width':'230px','height':'230px'});
})
$('#update').click(function () {
    ifSpeImg = 'false';
    $('#imageHead').css({'width':'750px','height':'750px'});
})

//保存修改
$('#save').click(function(){
    if($('#avatar-name').html()==""){
        alert('请选择图片');
    }else{
        $('#save').attr('data-dismiss','modal')
    }
})



